#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Created on 2011/04/13

@author: Rafael
'''

import os
if(os.name == "posix"):
    import matplotlib
    matplotlib.use('QT4Agg')
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
    pass
import numpy as np
import matplotlib.pyplot as plt
import sqlite3
from SqlInstructions import SqlInstructions

class CreateGraf():  
    def __init__(self, anos, tipoGraf):
        
        self.sql = SqlInstructions()
        if(tipoGraf == "nDocentesAno"):
            self.nDocentesAno(anos, tipoGraf)
            pass
        if(tipoGraf == "nDocentesInst"):
            self.DocentesInst(anos, tipoGraf)
            pass
        if(tipoGraf == "GrauDocentes"):
            self.grauDocentes(anos, tipoGraf)
            pass
        pass 
    
    
    """
    Create a Graphic with the years choosen by the user 
    and the number of teachers in the selected years
    """
    def nDocentesAno(self, anos, tipoGraf):
        
        info = []
        years = []
        yearsTxt = []
        for ano in anos:
            years.append(ano)
            yearsTxt.append("200{0}".format(ano))
            info.append(self.sql.doQueriesGraf(ano, tipoGraf))
            pass
        
        plt.bar(years, info, width=0.6, bottom=0, color='r')    
        plt.xticks(years, (yearsTxt) )
        plt.title('Total do Numero de Professores por Ano')
        plt.grid(False)
        plt.axis([-1, 10, min(info)-500, max(info)+500])
        plt.show()
        
        pass
    
    """
    Create a Graphic with the number of teachers
    in 10 institutions per selected year
    """
    def DocentesInst(self, anos, tipoGraf):
        
#        color = ["#ff0000", "#0000ff", "#17c001", "#c001a7", "#0bf0ed", 
#                 "#e8f00b", "#c8c8c0", "#000000", "#ff6000", "#7a2e00"]
        info = []
        yearsTxt = []
        #plots = []
        i = []
        for j in range(1,11):
            i.append(j)
            pass
        
        for ano in anos:
            info = self.sql.doQueriesGraf(ano, tipoGraf)
            
            yearsTxt.append("200{0}".format(ano))
            
            plt.bar(i, info[1], width=0.6, bottom=0, color='r')
            #plots.append(plt.plot(i, info[1], 's', color=color[ano]))
            plt.xticks(i, (info[0]), rotation='vertical', verticalalignment='bottom', horizontalalignment='right', size = 10)
            plt.xlabel('Estabelecimentos')
            plt.title('Numero de Professores por Instituicao de 200{0}'.format(ano))
            plt.grid(True)
            plt.axis([0, len(info[0])+2, min(info[1])-10, max(info[1])+10])
            plt.show()
            #plt.plot()
            pass
        
        pass
    
    """
    Create a Graphic with the number of teachers
    per degree per selected year
    """
    def grauDocentes(self, anos, tipoGraf):
        
        #Color for the lines in the graphic
        color = ["#ff0000", "#0000ff", "#17c001", "#c001a7", "#0bf0ed", 
                 "#e8f00b", "#c8c8c0", "#000000", "#ff6000", "#7a2e00"]
        
        #get information from sql
        i = []
        yearsTxt = []
        dic = {}
        for ano in anos:
            info = self.sql.doQueriesGraf(ano, tipoGraf)
            yearsTxt.append("200{0}".format(ano))
            for grau, nD in info.iteritems():
                #Correction of degree - Its needed because the name 
                #of the degrees varies with the years
                if(grau == "Doutor"):
                    grau = "Doutoramento"
                    pass
                if(grau == "Mestre"):
                    grau = "Mestrado"
                    pass
                if(grau == "Bacharel"):
                    grau = "Bacharelato"
                    pass
                if(grau == "Licenciado"):
                    grau = "Licenciatura"
                    pass
                dic[grau,ano] = nD
                pass
            i.append(ano)
            pass
        
        #create a list with the degrees
        listagrau = []
        for grau, nD in info.iteritems():
            #Correction of degree - Its needed because the name 
            #of the degrees varies with the years
            if(grau == "Doutor"):
                grau = "Doutoramento"
                pass
            if(grau == "Mestre"):
                grau = "Mestrado"
                pass
            if(grau == "Bacharel"):
                grau = "Bacharelato"
                pass
            if(grau == "Licenciado"):
                grau = "Licenciatura"
                pass
            listagrau.append(grau)
            pass
        
        #Put the information in the correct order to draw the graphic
        grauNDocente = []
        for grau in listagrau:
            graus=[]
            for ano in anos:
                graus.append(dic[grau, ano])
                pass
            grauNDocente.append(graus)
            pass
        
        #Draw the graphic
        z = 0;
        minimo = 0
        maximo = 0
        plots = []
        for inf in grauNDocente:
            #do this verification because if the user choose only 
            #one year its necessary to put dots on the graphic
            if(len(inf) == 1):
                plots.append(plt.plot(i, inf, 'o', color=color[z]))
                pass
            else:
                plots.append(plt.plot(i, inf, color=color[z]))
                pass
            #change the color of the lines
            z += 1
            #gets the max and min value to axis
            if(min(inf) < minimo):
                minimo = min(inf)
                pass
            if(max(inf) > maximo):
                maximo = max(inf)
                pass
            pass

        #properties of the graphic
        plt.xticks(i, (yearsTxt))
        plt.xlabel('Anos')
        plt.title('Numero de Professores por Grau')
        plt.grid(True)
        plt.axis([-1, 10, minimo-1000, maximo+15000])
        
        plt.legend( (plots), (listagrau), loc=9 )
        plt.show()
        pass
pass